package cn.com.anypay.manager.miaoma.suantaiqrcode.handler.impl;

import cn.com.anypay.manager.common.utils.HtmlUtils;
import cn.com.anypay.manager.miaoma.suantaiqrcode.SuantaiQrcodeEntity;
import cn.com.anypay.manager.miaoma.suantaiqrcode.handler.AbstractQrCodeHandler;
import cn.com.anypay.manager.miaoma.suantaiqrcode.dto.QrCodeGatewayResponse;
import cn.com.anypay.manager.common.response.ApiResponse;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 文本内容类型二维码处理器 (type = 2)
 *
 * 处理纯文本内容的二维码，通常显示联系方式、公司信息等
 * 由于HTTP重定向只能跳转到URL，这里生成一个显示文本的页面
 */
@Slf4j
@Component
public class TextQrCodeHandler extends AbstractQrCodeHandler {

    private static final Integer SUPPORTED_TYPE = 2;
    private static final String HANDLER_NAME = "TextQrCodeHandler";

    @Override
    public ApiResponse<Object> handle(SuantaiQrcodeEntity qrcode, String id) {
        logHandleStart(id);

        if (!isValidContent(qrcode.getContent())) {
            logHandleComplete(id, "Content is empty");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Content is empty");
        }

        JsonNode content = parseJsonContent(qrcode.getContent());
        if (content == null) {
            logHandleComplete(id, "Failed to parse JSON content");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Invalid JSON content");
        }

        String text = extractTextContent(content);
        if (text == null || text.trim().isEmpty()) {
            logHandleComplete(id, "No text content found");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "No text content found");
        }

        // 生成一个显示文本的页面URL
        String displayUrl = generateTextDisplayUrl(text, qrcode.getQrCodeName());

        logHandleComplete(id, "Redirecting to text display page");
        return createRedirectResponse(displayUrl);
    }

    /**
     * 从JSON内容中提取文本
     *
     * @param content JSON内容
     * @return 文本内容
     */
    private String extractTextContent(JsonNode content) {
        JsonNode textNode = content.get("text");
        return textNode != null ? textNode.asText() : null;
    }

    /**
     * 生成显示文本的页面URL
     *
     * 这里可以跳转到一个专门显示文本内容的页面
     * 或者生成data:text/html的URL直接显示内容
     *
     * @param text 文本内容
     * @param title 标题
     * @return 显示页面的URL
     */
    private String generateTextDisplayUrl(String text, String title) {
        try {
            // 方案1: 使用data URL直接显示HTML内容
            String html = generateTextDisplayHtml(text, title);
            String encodedHtml = URLEncoder.encode(html, StandardCharsets.UTF_8);
            return "data:text/html;charset=utf-8," + encodedHtml;

            // 方案2: 如果不支持data URL，可以跳转到专门的文本显示页面
            // String encodedText = URLEncoder.encode(text, StandardCharsets.UTF_8);
            // String encodedTitle = URLEncoder.encode(title, StandardCharsets.UTF_8);
            // return "/text-display.html?text=" + encodedText + "&title=" + encodedTitle;
        } catch (Exception e) {
            log.error("Failed to generate text display URL", e);
            return "data:text/plain;charset=utf-8," + text;
        }
    }

    /**
     * 生成显示文本的HTML内容
     */
    private String generateTextDisplayHtml(String text, String title) {
        return HtmlUtils.generateTextDisplayHtml(text, title);
    }

    // 删除escapeHtml方法（第153行）
    private String escapeHtml(String input) {
        if (input == null) return "";
        return input.replace("&", "&amp;")
                   .replace("<", "&lt;")
                   .replace(">", "&gt;")
                   .replace("\"", "&quot;")
                   .replace("'", "&#x27;");
    }

    @Override
    public Integer getSupportedType() {
        return SUPPORTED_TYPE;
    }

    @Override
    public String getHandlerName() {
        return HANDLER_NAME;
    }

    @Override
    public ApiResponse<Object> handleForGateway(SuantaiQrcodeEntity qrcode, String id) {
        logHandleStart(id);

        if (!isValidContent(qrcode.getContent())) {
            logHandleComplete(id, "Content is empty");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Content is empty");
        }

        JsonNode content = parseJsonContent(qrcode.getContent());
        if (content == null) {
            logHandleComplete(id, "Failed to parse JSON content");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "Invalid JSON content");
        }

        String text = extractTextContent(content);
        if (text == null || text.trim().isEmpty()) {
            logHandleComplete(id, "No text content found");
            return createErrorResponse(HttpStatus.BAD_REQUEST, "No text content found");
        }

        // 为网关模式返回结构化数据
        logHandleComplete(id, "Preparing text display data for gateway");
        return createGatewayDisplayResponse(
            qrcode.getQrCodeId(),
            qrcode.getQrCodeName(),
            qrcode.getQrCodeType(),
            QrCodeGatewayResponse.DisplayType.TEXT,
            text,
            qrcode.getQrCodeName(),
            "文本内容"
        );
    }
}